import { Button, Form, FormInstance, Input, Upload, UploadFile } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import React, { useEffect, useRef, useState } from "react";
import { RcFile, UploadProps } from "antd/lib/upload";
import useMessage from "@/hooks/useMessage";
import styles from "./index.module.less";
import { uploadFile } from "@/api/modules/common";
import { addAlbumApi, updateAlbumApi } from "@/api/modules/album";
import { DataType } from "../AlbumList";

interface PropsType {
	type?: string;
	album?: DataType;
	onComfirm?: () => void;
}

const AlbumAdd: React.FC<PropsType> = props => {
	const { type, album } = props;

	const { contextHolder, success, error } = useMessage();

	const formRef = useRef<FormInstance | null>(null);

	const [fileList, setFileList] = useState<UploadFile[]>([]);

	useEffect(() => {
		formRef.current?.setFieldsValue({
			album_name: album?.album_name
		});
	}, [album]);

	const handleUpload = async () => {
		const formData = new FormData();
		fileList.forEach(file => {
			formData.append("file", file as RcFile);
		});
		const res = await uploadFile(formData);
		return res.data;
	};

	const uploadProps: UploadProps = {
		onRemove: file => {
			const index = fileList.indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			setFileList(newFileList);
		},
		beforeUpload: file => {
			setFileList([...fileList, file]);
			return false;
		},
		fileList,
		maxCount: 1
	};

	const onFinish = async (values: any) => {
		try {
			let album_cover;
			if (fileList.length > 0) {
				const files = await handleUpload();
				album_cover = files.images[0].imageUrl;
			}
			if (type) {
				updateAlbumApi({ ...values, id: album?.id, album_cover });
			} else {
				addAlbumApi({ ...values, album_cover });
			}
			props.onComfirm && props.onComfirm();
			formRef.current?.resetFields();
			success("发布成功");
		} catch (err) {
			error("发布失败");
		}
	};

	return (
		<div className={styles.root}>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={{ top: 0 }}
			>
				<Form.Item label="名称" name="album_name">
					<Input />
				</Form.Item>
				<Form.Item label="文件" valuePropName="fileList">
					<Upload listType="picture-card" {...uploadProps}>
						{fileList.length < 1 && (
							<div>
								<PlusOutlined />
								<div style={{ marginTop: 8 }}>上传文件</div>
							</div>
						)}
					</Upload>
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default AlbumAdd;
